<?php


namespace App\Services;


use alipay\aop\AopClient;
use alipay\aop\AopCertClient;
use antcloud\AntCloudSDKCore\AntCloudClient;
use App\Exceptions\ApiErrorException;
use App\Models\AppTypeModel;
use App\Models\OrderSyncLog;

class AlipayBaseService
{
    const ALIPAY_SUCCESS_CODE = 10000;
    const LOG_TYPE_ORDER_INFO = 1; // 订单中心
    const LOG_TYPE_ORDER_ZM = 2; // 芝麻信用履约

    /**
     * 支付宝
     * @param $message
     * @param array $request
     * @param array $response
     */
    public static function requestLog($message, $request = [], $response = [])
    {
        $content = [
            'request' => is_object($request) ? object_array($request) : $request,
            'response' => is_object($response) ? object_array($response) : $response,
        ];
        \Illuminate\Support\Facades\Log::channel("alipaylog")->debug($message, $content);
    }

    /**
     * log
     * @param $orderId
     * @param $orderParams
     * @param $orderResult
     * @param $type
     * @param bool $flag
     */
    public static function addLog($orderId, $orderParams, $orderResult, $type, $flag = true)
    {
        $logData = [
            'order_id' => $orderId,
            'request_params' => json_encode($orderParams),
            'result_params' => json_encode($orderResult),
            'status' => $flag ? 1 : 0,
            'type' => $type,
        ];
        OrderSyncLog::query()->insert($logData);
    }


    /**
     * 移动/网页应用
     * @return AopClient
     */
    public static function aliPayRequest()
    {
        $aop = new AopClient ();
        $aop->gatewayUrl = config('alipay.gateway');
        $aop->appId = config('alipay.appId');
        $aop->rsaPrivateKey = config('alipay.privateKey');
        $aop->alipayrsaPublicKey = config('alipay.publicKey');
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        return $aop;
    }


    /**
     * 小程序
     * @return AopClient
     * @throws ApiErrorException
     */
    public static function aliPayXxzRequest($miniId = 0): AopClient
    {
        if ($miniId == 0) {
            throw new ApiErrorException("初始化支付宝客户端失败", "初始化支付宝客户端失败");
        } else {
            $appConfig = AppTypeModel::findById($miniId)->toArray();
        }

        $aop = new AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $appConfig['app_id'];
        $aop->rsaPrivateKey = $appConfig['app_cert_private_key'];
        $aop->alipayrsaPublicKey = $appConfig['alipay_cert_public_key'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        // if (isset($header['referer'][0]) && $header['referer'][0]) {
        //     if (strpos($header['referer'][0], '2021003177608366') !== false) {
        //         $aop->gatewayUrl = config('alipaydlz.gateway');
        //         $aop->appId = config('alipaydlz.xxz_appId');
        //         $aop->rsaPrivateKey = config('alipaydlz.xxz_privateKey');
        //         $aop->alipayrsaPublicKey = config('alipaydlz.xxz_publicKey');
        //     }
        // }

        return $aop;
    }


    /**
     * 格式化支付宝返回结果
     * @param $alipayRequest
     * @param $result
     * @return array
     */
    public static function methodFormat($alipayRequest, $result)
    {
        $responseNode = str_replace(".", "_", $alipayRequest->getApiMethodName()) . "_response";
        if (isset($result->$responseNode)) {
            return ['status' => true, 'data' => object_array($result->$responseNode)];
        }
        return ['status' => false, 'data' => object_array($result)];
    }


    public static function gender($gender)
    {
        switch ($gender) {
            case 'm':
                $genderChar = '男';
                break;
            case 'f':
                $genderChar = '女';
                break;
            default:
                $genderChar = '无';
        }
        return $genderChar;
    }

    /**
     * 蚂蚁集团
     * @return AntCloudClient
     */
    public static function getAntCloudClient()
    {
        $client = new AntCloudClient(
            'https://openapi.antchain.antgroup.com/gateway.do',
            'ACy4VGdEiUEiZbpM',
            'qQxKEoqUrU8qYiVH5JmCu33ASCt5n4fa'
        );
        // dd($client);
        return $client;

    }

    /**
     * 提现 网页应用
     * @return AopCertClient
     */
    public static function aliPayXxzCertRequest()
    {
        $aop = new AopCertClient;
        //$alipayCertPath = "支付宝公钥证书路径（要确保证书文件可读），例如：/home/admin/cert/alipayCertPublicKey_RSA2.crt";
        $alipayCertPath = dirname(dirname(dirname(__FILE__))) . '/vendor/alipay/cert/alipayCertPublicKey_RSA2.crt';
        //$appCertPath = "应用证书路径（要确保证书文件可读），例如：/home/admin/cert/appCertPublicKey.crt";
        $appCertPath= dirname(dirname(dirname(__FILE__))) . '/vendor/alipay/cert/appCertPublicKey_2021005136683108.crt';
        //$rootCertPath = "支付宝根证书路径（要确保证书文件可读），例如：/home/admin/cert/alipayRootCert.crt";
        $rootCertPath = dirname(dirname(dirname(__FILE__))) . '/vendor/alipay/cert/alipayRootCert.crt';
        $aop->gatewayUrl = config('alipay.gateway');
        $aop->appId = config('alipay.xxz_cert_appId');
        $aop->rsaPrivateKey = config('alipay.xxz_cert_privateKey');
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        // 调用getPublicKey从支付宝公钥证书中提取公钥
        $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
        // 是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $aop->isCheckAlipayPublicCert = true;
        // 调用getCertSN获取证书序列号
        $aop->appCertSN = $aop->getCertSN($appCertPath);
        // 调用getRootCertSN获取支付宝根证书序列号
        $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);
        return $aop;
    }

}
